<?php

namespace MoChat\App\Call\Service;

use Hyperf\DbConnection\Db;
use MoChat\App\Call\Constants\CallPlanIsExportNextTaskCode;
use MoChat\App\Call\Contract\CallPlanContract;
use MoChat\App\Call\Model\CallPlan;
use MoChat\App\Call\Model\CallPlanWorkContact;
use MoChat\Framework\Service\AbstractService;

class CallPlanService extends AbstractService implements CallPlanContract
{
    public function createAllContract($where): array
    {
        $all = $this->model->where($where)->select([
            'id',
            'name',
        ])->get();
        return empty($all) ? [] : $all->toArray();
    }
    /**
     * @var CallPlan
     */
    protected $model;

    public function deleteContract($id): int
    {
        return $this->model->deleteOne($id);
    }

    public function createContract($data)
    {
        $this->model->createOne($data);
    }

    public function getIndexContract($where, array $filed = ['*']): array
    {
        $list = $this->model->getPageList($where, $filed);
        if (!empty($list['data'])) {
            $ids = array_column($list['data'], 'id');
            //未完成
            $incompleteWorkContact = CallPlanWorkContact::whereIn('call_plan_id', $ids)->select([
                Db::raw('COUNT(*) as `count`'),
                'call_plan_id',
            ])->where('status', 0)->groupBy(['call_plan_id'])->get();
            //完成
            $completeWorkContact = CallPlanWorkContact::whereIn('call_plan_id', $ids)->select([
                Db::raw('COUNT(*) as `count`'),
                'call_plan_id',
            ])->where('status', 1)->groupBy(['call_plan_id'])->get();
            //未完成
            $incompleteWorkContact = empty($incompleteWorkContact) ? [] : array_column($incompleteWorkContact->toArray(), null, 'callPlanId');
            //完成
            $completeWorkContact = empty($completeWorkContact) ? [] : array_column($completeWorkContact->toArray(), null, 'callPlanId');
            foreach ($list['data'] as &$datum) {
                $key = $datum['id'];
                //未完成数
                $incompleteNumber = $incompleteWorkContact[$key]['count'] ?? 0;
                //完成数
                $completeNumber = $completeWorkContact[$key]['count'] ?? 0;
                $datum['totalTask'] = $incompleteNumber + $completeNumber;
                $datum['completeTask'] = $completeNumber;
                $datum['isExportNextTaskString'] = CallPlanIsExportNextTaskCode::getMessage($datum['isExportNextTask']);
            }
            unset($datum);
        }
        return $list;
    }

    public function updateContract($id, $data): int
    {
        return $this->model->updateOneById($id, $data);
    }
}